#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(TEST_TARGET_slup)
#include <varch/command.h>
#include <varch/unitt.h>
#include <varch/slup.h>
#include <varch/cQueue.h>
#else  
#include "init.h"
#include "command.h"
#include "unitt.h"
#include "kern.h"
#include "slup.h"
#include "cQueue.h"
#endif

/************************************************************************************/
/************************************* Unit Test ************************************/
/************************************************************************************/

// #define EXIT_TEST
extern uint64_t unitt_clock(void);

static int test_0(void)
{
    for (int i = 0; i < 100; i++)
    {
        if (0) 
        {
            
            #if defined (EXIT_TEST)
            exit(0);
            #endif 
            return UNITT_E_FAIL;
        }
    }
    
    return UNITT_E_OK;
}

static void unitt_task(void)
{
    static UNITT_TCASE rand_tests[] = {
        UNITT_TCASE(test_0),
        // UNITT_TCASE(test_1),
        // UNITT_TCASE(test_2),
    };

    static UNITT suites[] = {
        { "xxx suite", rand_tests, sizeof(rand_tests) / sizeof(rand_tests[0]) , unitt_clock },
    };

    UNITT_EXE(suites);
}

/************************************************************************************/
/************************************* Base Test ************************************/
/************************************************************************************/

//////////// sim uart dev ////////////
typedef void (*uart_rx_t)(char c);
static cQueue(char, 1024) qdev0;
static cQueue(char, 1024) qdev1;
static uart_rx_t dev0_rx = NULL;
static uart_rx_t dev1_rx = NULL;
static int dev0_uart_send(char c) { cQueue_push(qdev0, c); }
static int dev1_uart_send(char c) { cQueue_push(qdev1, c); }
static void dev0_uart_rxhandle(void) { char c = 0; while (cQueue_pop(qdev1, c)) { if (dev0_rx) dev0_rx(c); } }
static void dev1_uart_rxhandle(void) { char c = 0; while (cQueue_pop(qdev0, c)) { if (dev1_rx) dev1_rx(c); } }
static void dev0_uart_setrx(uart_rx_t rx) { dev0_rx = rx; }
static void dev1_uart_setrx(uart_rx_t rx) { dev1_rx = rx; }
//////////////////////////////////////

static uint32_t crc8(uint8_t* data, uint16_t len);
static int dev0_slup_receive(uint8_t *data, uint16_t length);
static int dev1_slup_receive(uint8_t *data, uint16_t length);

static SLUP slup0 = {
    .cfg = {
        .head = {'H', 'E', 'A', 'D'},
        .tail = {'T', 'A', 'I', 'L'},
        .hsize = SLUP_HEAD_MAX,
        .tsize = SLUP_TAIL_MAX,
        .csize = sizeof(uint8_t),
        .ssize = sizeof(uint32_t),
    },
    .period = 5,
    .putc = dev0_uart_send,
    .check = crc8,
    .receive = dev0_slup_receive,
};
static SLUP slup1 = {
    .cfg = {
        .head = {'H', 'E', 'A', 'D'},
        .tail = {'T', 'A', 'I', 'L'},
        .hsize = SLUP_HEAD_MAX,
        .tsize = SLUP_TAIL_MAX,
        .csize = sizeof(uint8_t),
        .ssize = sizeof(uint32_t),
    },
    .period = 5,
    .putc = dev1_uart_send,
    .check = crc8,
    .receive = dev1_slup_receive,
};

static void dev0_uart_receive(char c)
{
    slup_getc(&slup0, c);
}

static void dev1_uart_receive(char c)
{
    slup_getc(&slup1, c);
}

static uint32_t crc8(uint8_t* data, uint16_t len)
{
    uint8_t i;
    uint8_t crc = 0;
    while (len--)
    {
        crc ^= *data++;
        for (i = 0; i < 8; i++)
        {
            if (crc & 0x80) crc = (crc << 1) ^ 0x07;
            else crc <<= 1;
        }
    }
    return (uint32_t)crc;
}

static int dev0_slup_receive(uint8_t *data, uint16_t length)
{
    printf("length %d\r\n", length);
    return 0;
}

static int dev1_slup_receive(uint8_t *data, uint16_t length)
{
    printf("length %d\r\n", length);
    printf("%s\r\n", data);
    return 0;
}

static void dev0_slup_task(void)
{
    static uint32_t count = 0;

    count += 5;
    if (count >= 25200000) count = 0;

    if (count % 5 == 0)
    {
        slup_task(&slup0);
    }

    if (count % 1000 == 0)
    {
        uint8_t link = 0;
        slup_link_status(&slup0, &link);
        printf("dev0[%02x] send...\r\n", link);
        slup_send(&slup0, "0123456789", 10);
    }
}

static void dev1_slup_task(void)
{
    slup_task(&slup1);
}

static void test_base(void)
{
    printf("slup test!\r\n");

    /* uart dev init */
    cQueue_init(qdev0);
    cQueue_init(qdev1);
    dev0_uart_setrx(dev0_uart_receive);
    dev1_uart_setrx(dev1_uart_receive);
    task_create(5, dev0_uart_rxhandle);
    task_create(5, dev1_uart_rxhandle);

    /* slup protcol init */
    slup_init(&slup0);
    slup_init(&slup1);
    task_create(5, dev0_slup_task);
    task_create(5, dev1_slup_task);
}

/************************************************************************************/
/*************************************  Command  ************************************/
/************************************************************************************/

static void usage(void)
{
    printf(
"Usage: slup [opt] [arg] ...\n"
"\n"
"options:\n"
"    -e <execute>        Specifies the function to execute, the default is the <base> test\n"
"                        <base>      Test base function\n"
"                        <ut>        Unit test\n"
"    -h                  Print help\n"
"    -v                  Print version\n"
"    -u [<period>]       Unit test period, unit ms, the default is 1000ms\n"
"\n"

    );
}

static int test(int argc, char *argv[])
{
    char *execute = NULL;
    int ut_period = 1000;
    int period = 1000; // ms

    /* reset getopt */
    command_opt_init();

    while (1)
    {
        int opt = command_getopt(argc, argv, "e:hvu::p:");
        if (opt == -1) break;

        switch (opt) 
        {
        case 'p' :
            period = atoi(command_optarg);
            break;
        case 'u' :
            if (command_optarg) ut_period = atoi(command_optarg);
            break;
        case 'e' :
            execute = command_optarg;
            break;
        case 'v' :
            printf("slup version %d.%d.%d\r\n", SLUP_V_MAJOR, SLUP_V_MINOR, SLUP_V_PATCH);
            return 0;
        case '?':
            printf("Unknown option `%c`\r\n", command_optopt);
            return -1;
        case 'h' : 
        default:
            usage();
            return 0;
        }
    }
    
    if (execute)
    {
        if (!strcmp(execute, "base"))
        {
            test_base();
        }
        else if (!strcmp(execute, "ut"))
        {
            #if defined(TEST_TARGET_slup)
            while (1)
            {
                unitt_task();
                usleep(1000 * ut_period);
            }
            #else  
            printf("create task %d\r\n", task_create(ut_period, unitt_task));
            #endif
        }
    }
    else  
    {
        test_base();
    }
    
    return 0;
}

/************************************************************************************/
/************************************ Test entry ************************************/
/************************************************************************************/

#if defined(TEST_TARGET_slup)
int main(int argc, char *argv[])
{
    return test(argc, argv);
}
#else 
void test_slup(void)
{
    command_export("slup", test);
}
init_export_app(test_slup);
#endif 
